// index.js
const { PageBottomPadding } = require('../../utils/index.js');
const apiService = require('../../utils/apiService.js');

Page({
  data: {
    pageBottomStyle: '',
    allRooms: [],
    totalRooms: 0,
    activeRooms: 0,
    totalOrders: 0,
    refreshing: false,
    showRoomActionSheet: false,
    currentRoom: null,
    hasLoaded: false,
    roomActions: [
      { name: '进入房间', value: 'enter' },
      { name: '分享房间', value: 'share' },
      { name: '置顶/取消置顶', value: 'pin' },
      { name: '删除房间', value: 'delete' }
    ],
    // 主要功能（房间相关）
    mainFeatures: [
      {
        key: 'quick-order',
        title: '快速点单',
        subtitle: '智能进入',
        image: '/images/order.png',
        highlight: true
      },
      {
        key: 'create-room',
        title: '创建房间',
        subtitle: '开始点餐',
        image: '/images/order.png',
        highlight: false
      },
      {
        key: 'join-room',
        title: '加入房间',
        subtitle: '输入邀请码',
        image: '/images/orders.png',
        highlight: false
      }
    ],
    
    // 次要功能
    secondaryFeatures: [
      {
        key: 'room-history',
        title: '房间历史',
        desc: '查看历史房间',
        image: '/images/profile.png'
      }
    ]
  },

  onLoad() {
    // 检查登录状态
    const authGuard = require('../../utils/authGuard.js');
    const isLoggedIn = authGuard.checkLoginStatus();
    
    if (!isLoggedIn) {
      // 未登录时跳转到登录页面
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 已登录，加载数据
    this.loadRoomData();
    this.setPageBottomPadding();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.setPageBottomPadding();
    
    // 检查登录状态，但不强制跳转
    const authGuard = require('../../utils/authGuard.js');
    const isLoggedIn = authGuard.checkLoginStatus();
    
    // 如果已经加载过数据，检查是否需要刷新房间数据（从其他页面返回时）
    if (this.data.hasLoaded && isLoggedIn) {
      this.refreshRoomDataIfNeeded();
    }
  },

  // 检查是否需要刷新房间数据（新增方法）
  refreshRoomDataIfNeeded() {
    const app = getApp();
    const currentRoom = app.globalData.currentRoom;
    
    // 如果当前有活跃房间，检查是否需要更新房间信息
    if (currentRoom && currentRoom.roomId) {
      
      // 检查全局房间数据是否与当前房间信息一致
      const userRooms = app.globalData.userRooms || [];
      const roomInList = userRooms.find(room => room.room_id === currentRoom.roomId);
      
      if (roomInList) {
        // 更新房间的最后活跃时间
        const updatedRooms = userRooms.map(room => {
          if (room.room_id === currentRoom.roomId) {
            return {
              ...room,
              last_active: Date.now(),
              members_count: currentRoom.participantCount || room.members_count,
              current_round: currentRoom.currentRound || room.current_round
            };
          }
          return room;
        });
        
        // 更新全局数据
        app.globalData.userRooms = updatedRooms;
        
        // 更新页面显示
        this.updatePageRoomDisplay(updatedRooms);
        
      }
    } else {
      // 如果没有当前房间，重新加载房间数据（处理新建房间的情况）
      this.loadRoomData();
    }
  },

  // 更新页面房间显示（新增方法）
  updatePageRoomDisplay(updatedRooms) {
    // 更新页面数据
    this.setData({
      allRooms: updatedRooms,
      totalRooms: updatedRooms.length,
      activeRooms: updatedRooms.length,
      totalOrders: this.calculateTotalOrders(updatedRooms)
    });
    
    // 保存到本地存储
    wx.setStorageSync('allRooms', updatedRooms);
    
    // 更新全局房间数据
    const app = getApp();
    app.globalData.userRooms = updatedRooms;
  },


  // 加载房间数据
  async loadRoomData() {
    try {
      // 先设置空数据
    this.setData({
      allRooms: [],
      totalRooms: 0,
      activeRooms: 0,
      totalOrders: 0
    });
      
      // 获取用户所有房间数据
      const roomsResult = await apiService.getMyRooms();
      
      // 处理房间数据
      let allRooms = [];
      if (roomsResult && roomsResult.rooms) {
        allRooms = roomsResult.rooms;
      }
      
      // 更新页面数据
      this.setData({
        allRooms,
        totalRooms: allRooms.length,
        activeRooms: allRooms.length,
        totalOrders: this.calculateTotalOrders(allRooms),
        hasLoaded: true
      });
      
      // 保存到本地存储
      wx.setStorageSync('allRooms', allRooms);
      
      // 保存到全局状态（供点单页面使用）
      const app = getApp();
      app.globalData.userRooms = allRooms;
      
    } catch (error) {
      console.error('加载房间数据失败:', error);
      // 即使出错也要设置空数据
      this.setData({
        allRooms: [],
        totalRooms: 0,
        activeRooms: 0,
        totalOrders: 0,
        hasLoaded: true
      });
    }
  },

  // 计算总订单数
  calculateTotalOrders(rooms) {
    // 如果没有数据，返回0
    if (!rooms || rooms.length === 0) {
      return 0;
    }
    
    // 使用API返回的真实数据计算总订单数
    const totalOrders = rooms.reduce((total, room) => {
      // 使用total_orders字段，如果没有则默认为0
      return total + (room.total_orders || 0);
    }, 0);
    
    return totalOrders;
  },


  // 计算时间差
  getTimeAgo(timestamp) {
    const now = Date.now();
    const diff = now - timestamp;
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 60) {
      return minutes <= 0 ? '刚刚' : `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return new Date(timestamp).toLocaleDateString();
    }
  },

  // 处理功能入口点击
  onFeatureClick(e) {
    const feature = e.currentTarget.dataset.feature;
    
    switch (feature) {
      case 'quick-order':
        this.quickEnterOrder();
        break;
      case 'create-room':
        this.handleCreateRoom();
        break;
      case 'join-room':
        this.handleJoinRoom();
        break;
      case 'room-history':
        this.handleRoomHistory();
        break;
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
    }
  },

  // 创建房间
  handleCreateRoom() {
    wx.showModal({
      title: '创建房间',
      content: '选择创建临时房间或永久房间',
      confirmText: '创建',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/create-room/create-room'
          });
        }
      }
    });
  },

  // 快速进入点单（新增功能）
  quickEnterOrder() {
    const app = getApp();
    const userRooms = app.globalData.userRooms || [];
    
    if (userRooms.length === 0) {
      // 没有房间，提示创建
      wx.showModal({
        title: '还没有房间',
        content: '请先创建一个房间，然后开始点餐',
        confirmText: '去创建',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.handleCreateRoom();
          }
        }
      });
    } else if (userRooms.length === 1) {
      // 只有一个房间，直接进入
      this.enterRoom({ currentTarget: { dataset: { room: userRooms[0] } } });
    } else {
      // 多个房间，显示选择
      const roomNames = userRooms.map(room => room.title || '未命名房间');
      
      wx.showActionSheet({
        itemList: roomNames,
        success: (res) => {
          const selectedRoom = userRooms[res.tapIndex];
          this.enterRoom({ currentTarget: { dataset: { room: selectedRoom } } });
        }
      });
    }
  },

  // 更新房间显示（新增方法）
  updateRoomDisplay(enteredRoom) {
    const { allRooms } = this.data;
    
    // 更新房间列表
    const updatedRooms = allRooms.map(room => {
      if (room.room_id === enteredRoom.room_id) {
        return {
          ...room,
          members_count: enteredRoom.members_count || room.members_count,
          current_round: enteredRoom.current_round || room.current_round,
          last_active: Date.now() // 更新最后活跃时间
        };
      }
      return room;
    });
    
    // 更新页面数据
    this.setData({
      allRooms: updatedRooms,
      totalRooms: updatedRooms.length,
      activeRooms: updatedRooms.length,
      totalOrders: this.calculateTotalOrders(updatedRooms)
    });
    
    // 更新全局房间数据
    const app = getApp();
    app.globalData.userRooms = updatedRooms;
    
    // 保存到本地存储
    wx.setStorageSync('allRooms', updatedRooms);
    
  },

  // 加入房间
  handleJoinRoom() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },


  // 房间历史
  handleRoomHistory() {
    wx.navigateTo({
      url: '/pages/room-list/room-list'
    });
  },

  // 查看全部历史房间
  viewAllHistory() {
    wx.navigateTo({
      url: '/pages/room-list/room-list'
    });
  },


  // 跳转到创建房间页面
  navigateToCreateRoom(type) {
    wx.navigateTo({
      url: `/pages/create-room/create-room?type=${type}`
    });
  },


  // 通过邀请码加入房间
  async joinRoomByCode(code) {
    if (!code) {
      wx.showToast({
        title: '请输入邀请码',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '加入中...'
    });

    try {
      // 调用API加入房间
      const roomData = await apiService.joinRoom(code);
      
      wx.hideLoading();
      
      // 保存房间信息到全局数据（严格按照接口文档定义）
      const app = getApp();
      app.globalData.currentRoom = {
        roomId: roomData.room_id,           // 房间唯一标识
        roomTitle: roomData.title,          // 房间标题
        roomType: roomData.type,            // 房间类型
        roomDesc: roomData.description      // 房间描述
      };
      
      // 跳转到点单页面
      wx.switchTab({
        url: '/pages/order/order'
      });
      
    } catch (error) {
      wx.hideLoading();
      
      // 显示错误信息
      wx.showModal({
        title: '加入失败',
        content: error.message || '未找到对应的房间，请检查邀请码是否正确',
        showCancel: false,
        confirmText: '确定'
      });
    }
  },


  // 进入房间
  enterRoom(e) {
    const room = e.currentTarget.dataset.room;
    if (!room) {
      wx.showToast({
        title: '房间信息错误',
        icon: 'none'
      });
      return;
    }

    // 保存当前房间信息到全局数据（严格按照接口文档定义）
    const app = getApp();
    const roomData = {
      roomId: room.room_id,           // 房间唯一标识
      roomTitle: room.title,          // 房间标题
      roomType: room.type,            // 房间类型
      roomDesc: room.description,     // 房间描述
      participantCount: room.members_count,  // 参与人数
      currentRound: room.current_round       // 当前轮次
    };
    
    // 确保全局数据正确设置
    app.globalData.currentRoom = roomData;

    
    // 更新首页房间列表显示（实时更新）
    this.updateRoomDisplay(room);
    
    // 显示加载提示
    wx.showLoading({
      title: '进入房间中...'
    });

    // 跳转到订单页面（tabbar页面）
    wx.switchTab({
      url: '/pages/order/order',
      success: () => {
        wx.hideLoading();
        wx.showToast({
          title: '进入房间成功',
          icon: 'success'
        });
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '进入房间失败',
          icon: 'none'
        });
      }
    });
  },



  // 下拉刷新
  async onPullDownRefresh() {
    try {
      await this.loadRoomData();
    } catch (error) {
      console.error('下拉刷新失败:', error);
    } finally {
      setTimeout(() => {
        wx.stopPullDownRefresh();
      }, 1000);
    }
  },


  // 扫码功能
  scanQRCode() {
    wx.scanCode({
      success: (res) => {
        this.joinRoomByCode(res.result);
      },
      fail: (err) => {
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  // 显示房间操作菜单
  showRoomMenu(e) {
    const room = e.currentTarget.dataset.room;
    this.setData({
      currentRoom: room,
      showRoomActionSheet: true
    });
  },

  // 房间操作选择
  onRoomActionSelect(e) {
    const action = e.detail.value;
    const room = this.data.currentRoom;
    
    switch (action) {
      case 'enter':
        this.enterRoom({ currentTarget: { dataset: { room } } });
        break;
      case 'share':
        this.shareRoom(room);
        break;
      case 'pin':
        this.toggleRoomPin(room);
        break;
      case 'delete':
        this.deleteRoom(room);
        break;
    }
    
    this.setData({ showRoomActionSheet: false });
  },

  // 关闭房间操作菜单
  onCloseRoomActionSheet() {
    this.setData({ showRoomActionSheet: false });
  },

  // 分享房间
  shareRoom(room) {
    wx.showShareMenu({
      withShareTicket: true,
      success: () => {
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        });
      }
    });
  },

  // 切换房间置顶状态
  async toggleRoomPin(room) {
    try {
      const roomId = room.room_id;  // 严格按照接口文档定义
      
      if (room.is_pinned || room.pinned) {
        // 取消置顶
        await apiService.unpinRoom(roomId);
        
        // 更新本地数据
        const updatedRooms = this.data.allRooms.map(r => 
          r.room_id === roomId ? { ...r, is_pinned: false, pinned: false } : r
        );
        
        this.setData({
          allRooms: updatedRooms
        });
        
        wx.showToast({
          title: '已取消置顶',
          icon: 'success'
        });
      } else {
        // 置顶
        await apiService.pinRoom(roomId);
        
        // 更新本地数据
        const updatedRooms = this.data.allRooms.map(r => 
          r.room_id === roomId ? { ...r, is_pinned: true, pinned: true } : r
        );
        
        this.setData({
          allRooms: updatedRooms
        });
        
        wx.showToast({
          title: '已置顶',
          icon: 'success'
        });
      }
      
      // 保存到本地存储
      wx.setStorageSync('allRooms', this.data.allRooms);
      
    } catch (error) {
      
      // 降级到本地操作
      const roomId = room.room_id;  // 严格按照接口文档定义
      
      if (room.is_pinned || room.pinned) {
        // 取消置顶
        const updatedRooms = this.data.allRooms.map(r => 
          r.room_id === roomId ? { ...r, is_pinned: false, pinned: false } : r
        );
        
        this.setData({
          allRooms: updatedRooms
        });
        
        wx.showToast({
          title: '已取消置顶',
          icon: 'success'
        });
      } else {
        // 置顶
        const updatedRooms = this.data.allRooms.map(r => 
          r.room_id === roomId ? { ...r, is_pinned: true, pinned: true } : r
        );
        
        this.setData({
          allRooms: updatedRooms
        });
        
        wx.showToast({
          title: '已置顶',
          icon: 'success'
        });
      }
      
      // 保存到本地存储
      wx.setStorageSync('allRooms', this.data.allRooms);
    }
  },

  // 删除房间
  deleteRoom(room) {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除房间"${room.title}"吗？`,
      success: (res) => {
        if (res.confirm) {
          const updatedRooms = this.data.allRooms.filter(r => r.room_id !== room.room_id);
          
          this.setData({
            allRooms: updatedRooms,
            totalRooms: updatedRooms.length,
            activeRooms: updatedRooms.length,
            totalOrders: this.calculateTotalOrders(updatedRooms)
          });
          
          // 保存到本地存储
          wx.setStorageSync('allRooms', updatedRooms);
          
          // 更新全局数据
          const app = getApp();
          app.globalData.userRooms = updatedRooms;
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },



  // 设置页面底部间距
  setPageBottomPadding() {
    PageBottomPadding.setPagePadding(this);
  },

})
